package com.bookocean.infrastructure.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Web配置类
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源访问
        Path uploadDir = Paths.get(uploadPath);
        String uploadAbsolutePath = uploadDir.toFile().getAbsolutePath();
        
        registry.addResourceHandler("/api/file/**")
                .addResourceLocations("file:" + uploadAbsolutePath + "/");
        
        // 配置封面图片访问
        registry.addResourceHandler("/api/file/covers/**")
                .addResourceLocations("file:" + uploadAbsolutePath + "/covers/");
        
        // 配置默认封面图片访问
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加认证拦截器
        registry.addInterceptor(authenticationInterceptor)
                .addPathPatterns("/**")  // 拦截所有请求
                .excludePathPatterns(
                    "/bookOcean/user/login",           // 登录接口
                    "/bookOcean/user/updateUserAvatar", // 更新用户头像
                    "/bookOcean/daily-quote/getDailyQuote", // 每日一句接口
                    "/bookOcean/file/upload/cover",    // 封面上传接口
                    "/static/**",                      // 静态资源
                    "/api/file/**",                    // 文件访问
                    "/health",                         // 健康检查
                    "/actuator/**",                    // Spring Boot Actuator
                    "/swagger-ui/**",                  // Swagger UI
                    "/v3/api-docs/**",                // OpenAPI 文档
                    "/favicon.ico"                     // 图标
                );
    }
}
